package hu.arnoldfarkas.camel.dropbox;

import com.dropbox.core.DbxException;
import java.io.IOException;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.impl.DefaultProducer;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

public class DropboxProducer extends DefaultProducer {

    private static final transient Log LOG = LogFactory.getLog(DropboxProducer.class);
    private final DropboxEndpoint endpoint;

    public DropboxProducer(DropboxEndpoint endpoint) {
        super(endpoint);
        this.endpoint = endpoint;
    }

    public void process(Exchange exchange) throws Exception {
        final Map<String, Object> headers = exchange.getIn().getHeaders();
        String absolutePath = headers.get("CamelFileAbsolutePath").toString();
        String filename = headers.get("CamelFileNameOnly").toString();
        uploadByAbsoluteFilePath(absolutePath, filename);
    }

    private void uploadByAbsoluteFilePath(String absolutePath, String uploadName) {
        try {
            DropboxUploader uploader = new DropboxUploader(new DropboxClientFactory(endpoint.getUserId(), endpoint.getAccessToken()).getClient());
            uploader.uploadFile(absolutePath, uploadName);
        } catch (DbxException ex) {
            LOG.debug("upload error", ex);
        } catch (IOException ex) {
            LOG.debug("upload error", ex);
        }
    }

}

